//
//  lxLoginControllerViewController.m
//  luodansc
//
//  Created by 倫 星 on 2012/10/18.
//  Copyright (c) 2012年 方正株式会社. All rights reserved.
//

#import "lxLoginViewController.h"
#import "lxLoginInfoEntity.h"
#import "lxStringUtility.h"
#import "lxUserRegistViewController.h"

@interface lxLoginViewController ()
- (void)onLogin:(QButtonElement *)buttonElement;
- (void)onRegistView:(QButtonElement *)buttonElement;
- (void)onAbout;

@end

@implementation lxLoginViewController

- (QRootElement*)getLoginRoot {
    QRootElement *root = [[QRootElement alloc] init];
    root.title = NSLocalizedString(@"login", nil);
    root.grouped = YES;
    root.controllerName = @"lxLoginViewController";
    QSection *sectionLogin = [[QSection alloc] init];
    
    sectionLogin.title = NSLocalizedString(@"login", nil);
    
    QEntryElement *Login = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"username", nil) Value:@"" Placeholder:NSLocalizedString(@"username", nil)];
    Login.key = @"login";
    Login.bind = @"textValue:login";
    
    QEntryElement *Password = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"passwd", nil) Value:@"" Placeholder:NSLocalizedString(@"passwd", nil)];
    Password.key = @"password";
    Password.bind = @"textValue:password";
    Password.secureTextEntry = YES;
    
    [sectionLogin addElement:Login];
    [sectionLogin addElement:Password];
    
    QSection *sectionButton = [[QSection alloc] init];
    QButtonElement *loginButton = [[QButtonElement alloc] initWithTitle:NSLocalizedString(@"login", nil)];
    loginButton.controllerAction = @"onLogin:";
    [sectionButton addElement:loginButton];
    
    QButtonElement *registerButton = [[QButtonElement alloc] initWithTitle:NSLocalizedString(@"register", nil)];
    registerButton.controllerAction = @"onRegistView:";
    [sectionButton addElement:registerButton];
    
    [root addSection:sectionLogin];
    [root addSection:sectionButton];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"about", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onAbout)];
    
    return root;
}

- (QRootElement*)getLogoutRoot {
    QRootElement *root = [[QRootElement alloc] init];
    root.title = NSLocalizedString(@"user_info", nil);
    root.grouped = YES;
    root.controllerName = @"lxLoginViewController";
    QSection *section = [[QSection alloc] init];
    
    section.title = NSLocalizedString(@"user_info", nil);
    
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    
    NSString *str_user_name = @"";
    if (NO == [lxStringUtility isNil:[appContainer getUserInfoEntity].user_name]) {
        str_user_name = [appContainer getUserInfoEntity].user_name;
    }
    
    NSString *str_wellcome = [[NSString alloc] initWithFormat:@"%@  %@", str_user_name, NSLocalizedString(@"welcome", nil)];
    
    QTextElement *t_user_name = [[QTextElement alloc] initWithText:str_wellcome];

    [section addElement:t_user_name];
    
    NSString *last_time = @"";
    if (NO == [lxStringUtility isNil:[appContainer getUserInfoEntity].last_login]) {
        last_time = [appContainer getUserInfoEntity].last_login;
    }
    
    NSString *str_last_time = [[NSString alloc] initWithFormat:@"%@ %@", NSLocalizedString(@"last_login_time", nil), last_time];
    
    QTextElement *t_last_time = [[QTextElement alloc] initWithText:str_last_time];
    
   [section addElement:t_last_time];
    
    NSString *money = NSLocalizedString(@"money", nil);
    
    NSString *user_money = [lxStringUtility stringTrim:[NSString stringWithFormat:@"%10.2f", [appContainer getUserInfoEntity].user_money]];

    if (YES == [lxStringUtility isNil:user_money]) {
        user_money = @"0";
    }
    
    NSString *str_user_money = [[NSString alloc] initWithFormat:@"%@ %@%@", NSLocalizedString(@"user_money", nil), user_money, money];
    
    QTextElement *t_user_money = [[QTextElement alloc] initWithText:str_user_money];
    
    [section addElement:t_user_money];
    
    int pay_points = [appContainer getUserInfoEntity].pay_points;
    
    NSString *str_pay_points = [[NSString alloc] initWithFormat:@"%@ %d", NSLocalizedString(@"pay_points", nil), pay_points];
    
    QTextElement *t_pay_points = [[QTextElement alloc] initWithText:str_pay_points];
    
    [section addElement:t_pay_points];

    [root addSection:section];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"logout", nil) style:UIBarButtonItemStyleDone target:self action:@selector(logout)];
    
    return root;
}

- (id)init {
    self = [super init];
    if (nil != self) {
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];

        if (NO == [lxStringUtility isNil:[appContainer getUserInfoEntity].user_name]) {
            self.root = [self getLogoutRoot];
        } else {
            self.resizeWhenKeyboardPresented = YES;
            self.root = [self getLoginRoot];
        }
    }
    return self;
}

- (void)setQuickDialogTableView:(QuickDialogTableView *)aQuickDialogTableView {
    [super setQuickDialogTableView:aQuickDialogTableView];
    
    self.quickDialogTableView.backgroundView = nil;
    self.quickDialogTableView.backgroundColor = [UIColor colorWithHue:0.1174 saturation:0.7131 brightness:0.8618 alpha:1.0000];
    self.quickDialogTableView.bounces = NO;
    self.quickDialogTableView.styleProvider = self;
    
    ((QEntryElement *)[self.root elementWithKey:@"login"]).delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.tintColor = nil;
}

- (void)onLogin:(QButtonElement *)buttonElement {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    if (YES == [appContainer isExistNet]) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        lxLoginInfoEntity *info = [[lxLoginInfoEntity alloc] init];
        [self.root fetchValueUsingBindingsIntoObject:info];
    
        info.login = [lxStringUtility stringTrim:info.login];
        if ([lxStringUtility isNil:info.login]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"user_name_is_empty_msg", nil)
                                                    delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                    otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
    
        info.password = [lxStringUtility stringTrim:info.password];
        if ([lxStringUtility isNil:info.password]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"passwd_is_empty_msg", nil)
                                                    delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                    otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }

        [self loading:YES];
        [self sendRequest:info.login password:info.password isStartAsynchronous:YES];
    }
}

- (void)onRegistView:(QButtonElement *)buttonElement {
    lxUserRegistViewController *lxURVC = [[[lxUserRegistViewController alloc] init] autorelease];
    [self.navigationController pushViewController:lxURVC animated:YES];
}

- (void)onAbout {
    QRootElement *details = [lxLoginViewController createDetailsForm];
    
    QuickDialogController *quickform = [QuickDialogController controllerForRoot:details];
//    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:quickform] animated:YES completion: nil];
    [self.navigationController pushViewController:quickform animated:YES];
}

-(void)cell:(UITableViewCell *)cell willAppearForElement:(QElement *)element atIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor colorWithRed:0.9582 green:0.9104 blue:0.7991 alpha:1.0000];
    
    if ([element isKindOfClass:[QEntryElement class]] || [element isKindOfClass:[QButtonElement class]] || [element isKindOfClass:[QWebElement class]]){
        cell.textLabel.textColor = [UIColor colorWithRed:0.6033 green:0.2323 blue:0.0000 alpha:1.0000];
    }
}

+ (QRootElement *)createDetailsForm {
    QRootElement *details = [[QRootElement alloc] init];
    details.title = @"Details";
    details.controllerName = @"lxAboutController";
    details.grouped = YES;
    QSection *section = [[QSection alloc] initWithTitle:NSLocalizedString(@"information", nil)];
    [section addElement:[[QTextElement alloc] initWithText:NSLocalizedString(@"details_text", nil)]];
    [details addSection:section];
    return details;
}

- (BOOL)QEntryShouldChangeCharactersInRangeForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Should change characters");
    return YES;
}

- (void)QEntryEditingChangedForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Editing changed");
}


- (void)QEntryMustReturnForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Must return");
    
}

- (void)dealloc {
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (ASIHTTPRequest *)sendRequest:(NSString *)user_name password:(NSString *)password isStartAsynchronous:(BOOL)isStartAsynchronous {

    NSString *str_url = [NSString stringWithFormat:@"%@%@?user_name=%@&password=%@", service_url, getUserInfoServlet, user_name, password];
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    
    if (YES == isStartAsynchronous) {
        [request startAsynchronous];
    } else {
        [request startSynchronous];
    }
    return request;
}

- (BOOL)getResponse:(ASIHTTPRequest *)request {
    NSString *responseString = [request responseString];
    
    if (![responseString isKindOfClass:[NSString class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if ([lxStringUtility isNil:responseString]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    NSData *reponsedata = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (nil == reponsedata) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if (![reponsedata isKindOfClass:[NSData class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    __autoreleasing NSError *error = nil;
    
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reponsedata options:kNilOptions error:&error];
    if (nil == dictionary) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        return NO;
    }
    
    if (![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        return NO;
    }
    
    lxUserInfoEntity *userEntity = [[lxUserInfoEntity alloc] init];
    
    BOOL result = [userEntity setEntity:dictionary];
    if (YES == result) {
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
        
        lxLoginInfoEntity *info = [[lxLoginInfoEntity alloc] init];
        [self.root fetchValueUsingBindingsIntoObject:info];
        
        info.password = [lxStringUtility stringTrim:info.password];
        if (![lxStringUtility isNil:info.password]) {
            userEntity.password = info.password;
        }
        [appContainer setUserInfoEntity:userEntity];
    }
    
    return YES;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    [self loading:NO];
    BOOL result = [self getResponse:request];
    if (NO == result) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                            message:NSLocalizedString(@"user_name_or_passwd_error", nil)
                                            delegate:self
                                            cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                            otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];

    if (YES == [lxStringUtility isNil:[appContainer getUserInfoEntity].user_name]) {
        return;
    }
    
    if (YES == [lxStringUtility isNil:[appContainer getUserInfoEntity].password]) {
        return;
    }
    
    lxDBAccessor* dbAccessor = [lxDBAccessor sharedLxDBAccessor];
    [dbAccessor setUserInfo:[appContainer getUserInfoEntity]];
    
    self.root = [self getLogoutRoot];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                                                    message:NSLocalizedString(@"login_ok", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [self loading:NO];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"network_conn_failed", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (void)logout {
    lxDBAccessor* dbAccessor = [lxDBAccessor sharedLxDBAccessor];
    BOOL ret = [dbAccessor delUser];

    if (YES == ret) {
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
        [appContainer delUserInfoEntity];
        self.root = [self getLoginRoot];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                                                        message:NSLocalizedString(@"logout_ok", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                                                        message:NSLocalizedString(@"logout_ng", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

@end
